package cn.edu.zut.sunday.base.service.impl;

import cn.edu.zut.sunday.base.dao.GenericDao;
import cn.edu.zut.sunday.base.domain.BaseEntity;
import cn.edu.zut.sunday.base.service.GenericService;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * This class serves as the Base class for all other Managers - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * </p>
 * <p>
 * To register this class in your Spring context file, use the following XML.
 *
 * @param <T>  a type variable
 * @param <PK> the primary key for that type
 */
@Transactional
public class GenericServiceImpl<T extends BaseEntity<PK>, PK extends Serializable> implements
  GenericService<T, PK> {

    protected GenericDao<T, PK> dao;

    public void delete(PK id) {
        this.dao.deleteById(id);
    }

    public List<T> findAll() {
        return this.dao.findAll();
    }

    public Page<T> findAll(Specification<T> specification, Pageable page) {
        return this.dao.findAll(specification, page);
    }

    public Page<T> findAll(Pageable page) {
        return this.dao.findAll(page);
    }

    /**
     * 返回查询的数据对象
     * @param id entity id;
     * @return 如果存在则返回该对象，如果不存在返回null
     */
    public T findById(PK id) {
         return this.dao.findById(id).orElse(null);
    }

    public List<T> save(Iterable<T> entities) {
        return this.dao.saveAll(entities);
    }

    public T save(T entity) {
        return this.dao.save(entity);
    }

    @Override
    public void deleteAll() {
        this.dao.deleteAll();
    }

    @Override
    public long count() {
        return this.dao.count();
    }

}
